(async()=>{
	const {get_cookie,front_log,after_update,Get_apply_nos}=require('./api')
	const {handle,addCookies,close_fn}=require('./tools')
	const puppeteer = require('puppeteer');
	const os =require('os')
	const debug=os.type()!=='Linux'
	let apply_nos=await Get_apply_nos()
	apply_nos=apply_nos.data.apply_nos
	
	if(!apply_nos.length){
		const msg='暂无同步数据'
		front_log({ msg})
		close_fn(msg)
	}
	let cookie_str=await get_cookie()
	if(!cookie_str){
		const msg='多国cookie 为空'
		front_log({ msg})
		close_fn(msg)
	}
	
	const browser =await puppeteer.launch({ 
		headless: debug,
		devtools: false,
		ignoreDefaultArgs: ["--enable-automation"],
		args: ['--no-sandbox', '--disable-setuid-sandbox']
	}) 
	const page = await browser.newPage();
	await addCookies(cookie_str,page,'cpquery.cnipa.gov.cn')
	await page.goto('http://cpquery.cnipa.gov.cn/txnPantentInfoList.do?inner-flag:open-type=window&inner-flag:flowno='+new Date().getTime())
	if(!await page.$('#query')){
		const msg='多国查询cookie失效'
		front_log({msg})
		browser.close()
		close_fn(msg)
	}else{
		const func=function(arr){
		
			return Promise.all(arr.map(async el=>handle(el,browser)))
			.then(res=>{
				let err_arr=[],succ_arr=[]
				res.forEach((el,index)=>{
					let no=arr[index]
					if( typeof(el)=='string' || el.code!=0 ){
						err_arr.push(no)
					}else{
						succ_arr.push(no)
						after_update({apply_no:no})
					}
					
				})
				if(succ_arr.length)
					front_log({msg:`已成功同步：${succ_arr.length}条`+succ_arr.join(',')})
				if(err_arr.length)
					front_log({msg:`已失败同步：${err_arr.length}条`+err_arr.join(',')})
			})
			.catch(err=>{
				browser.close()
				console.log('内部错误:'+err);
				// close_fn(typeof(err)=='string'?err:'error')
			})
		}

		const loop_func=async function(){
			await func(JSON.parse(JSON.stringify(apply_nos)))
			const tmp=await Get_apply_nos()
			apply_nos=tmp.data.apply_nos 
			if(apply_nos&&!apply_nos.length){
				close_fn('已执行完毕')
				return
			}
			loop_func()
		}
		loop_func()
	}

})()



